package com.example.servletdemo.jdbc;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Objects;

@WebServlet(name = "besjdbc", value = "/besjdbc")
public class BESJDBCTest extends HttpServlet  {
    private String message;

    public void init() {
        message = "Hello World!";
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        Connection connection = null;
        Statement statement = null;
        try {
            InitialContext ctx = new InitialContext();
            Context comp_env = (Context) ctx.lookup("java:comp/env");
            DataSource ds = (DataSource) comp_env.lookup("db1");
            connection = ds.getConnection();
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(" SELECT name FROM muser WHERE id=1 ");
            String name = null;
            if (Objects.nonNull(resultSet)) {
                while (resultSet.next()) {
                    name = resultSet.getString("name");
                    System.out.println("=====" + name );
                }
            }
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h1>" + name + "</h1>");
            out.println("</body></html>");
        } catch (NamingException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (Objects.nonNull(statement)) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (Objects.nonNull(connection)) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void destroy() {
    }
}
